<?php
use Phalcon\Config;
use Phalcon\Mvc\Controller;
use Phalcon\Session\Adapter\Files as Session;
require_once(APP_PATH.'app/common/func.php');//公共函数
/**
	2016年7月16日
	公共可扩展函数
*/
class BaseController extends Controller
{
	public $C;//config对象
	public function pageInit()
	{
		$this->C = $this->C();
	}
	//加载公共扩展类
	public function loadClass($classname)
	{
		$file = APP_PATH.'app/common/'.$classname.'.php';
		if(is_file($file)) require_once($file);
	}
	//读取配置文件
	public function C()
	{
		require_once(APP_PATH.'app/common/config.php');
		$config = new Config($setting);
		return $config;
	}
	//登录检测  默认数据不进行反馈/$feek
	public function checkAuth($feek=false)
	{
		$user = $this->infoUser('user_name');
		if($user) return false;
		//数据反馈
		if($feek == true){
			return true;
		}
		return $this->forward('Error/show403');
	}
	protected function forward($uri)
    {
        $uriParts = explode('/', $uri);
        $params = array_slice($uriParts, 2);
    	return $this->dispatcher->forward(
    		array(
    			'controller' => $uriParts[0],
    			'action' => $uriParts[1],
                'params' => $params
    		)
    	);
    }
	//前端文件加载
	public function load($opt=null,$self=false)
	{
		//公共头部
		$opt = is_array($opt)? $opt:array();
		$c = $this->C();
		$ico = $c->app->icon;
		$xhtml = '
			<link rel="icon" href="'.$ico.'" type="image/x-icon" />
			<link rel="shortcut icon" href="'.$ico.'" type="image/x-icon" />
			<meta name="Author" content="Joshua Conero Doeeking">
			<meta name="Keywords" content="Conero 集团">
			<meta name="Description" content="个人网站项目设计">
		';
		if(isset($opt['script'])) $xhtml .= $opt['script'];
		$appname = app_name('app');
		if($self == false){
			$xhtml .= '
				<script src="/TeClan/public/js/jquery-1.12.4.min.js"></script>
				<script src="/TeClan/public/js/teclan.js"></script>
				<link href="/TeClan/public/css/TeClan.css" type="text/css" rel="stylesheet">
			';
		}
		//	自定义 js 目录下路径
		if(isset($opt['js_self'])){
			$tmpArr = is_array($opt['js_self'])? $opt['js_self']:array($opt['js_self']);
			foreach($tmpArr as $v){
				$xhtml .= '<script src="'.$c->app->js.$v.'.js"></script>';
			}
		}
		//	js
		if(isset($opt['js'])){
			$tmpArr = is_array($opt['js'])? $opt['js']:array($opt['js']);
			foreach($tmpArr as $v){
				$xhtml .= '<script src="'.$c->app->js.$appname.'/'.$v.'.js"></script>';
			}
		}
		//	css
		if(isset($opt['css'])){
			$tmpArr = is_array($opt['css'])? $opt['css']:array($opt['css']);
			foreach($tmpArr as $v){
				$xhtml .= '<link href="'.$c->app->css.$appname.'/'.$v.'.css" type="text/css" rel="stylesheet">';
			}
		}
		$title = isset($opt['title'])? $opt['title']:'首页';
		$this->view->setVars(array(
			'tpltitle'=>$title,
			'tplHead'=>$xhtml
		));
		//$this->debug($xhtml);
	}
	public function debug($data)
	{
		if(is_object($data)) $data = (array)$data;
		$logfile = APP_PATH.'log/'.date('Y-m-d').'.log';
		$fh = fopen($logfile,'a+');
		$data = is_array($data)? print_r($data,true):$data;
		$data = "\r\n~~~~~~~~~~~~~~~~~~~(".date('Y-m-d H:i:s')."),系统调试输出：\r\n".$data;
		fwrite($fh,$data);
		fclose($fh);
	}
	public function infoUser($key=null)
	{
		$session = new session();
		$data = $session->get('infoUser');
		if(!is_array($data) || empty($data)) return false;
		if($key){
			if(array_key_exists($key,$data)) return $data[$key];
			return null;
		}
		return $data;
	}
	public function baseData()
	{
		$data = array();
		$uinfo = $this->infoUser();
		if(empty($uinfo) || !is_array($uinfo) || count($uinfo)<1) return array();
		$data['mtime'] = date('Y-m-d H:i:s');
		$data['user_code'] = $uinfo['user_code'];
		$data['user_name'] = $uinfo['user_name'];
		return $data;

	}
	//数据库抽象层
	public function getDbObj()
	{
		return $this->db;
		/*历史数据，无法获取model的数据库对象时*/
		try{
			$opt = (array)$this->db;
		}catch(Exception $e){
			$opt = $this->C()->db;//重置
		}
		
		if(!is_array($opt)) return false;
		/*
		// 报错 Exception: SQLSTATE[HY000] [1193] Unknown system variable 'NAMES'
		$opt['options'] = array(
			PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES \'UTF8\'",
			PDO::ATTR_CASE => PDO::CASE_LOWER
		);
		*/
		
		$connection = new \Phalcon\Db\Adapter\Pdo\Mysql($opt);
		return $connection;
	}
	//Ajax数据返回
	public function ajaxReturn($data)
	{
		// 返回JSON数据格式到客户端 包含状态信息
		header('Content-Type:application/json; charset=utf-8;');
		exit(json_encode($data));
	}
	//	十进制分页-php动态
	public function dec2page($page,$url=null)
	{
		$xhtml = '';
		if(!is_object($page)) return $xhtml;
		$cur = $page->current;
		$all = $page->total_pages;

		$min = floor($cur/10);
        $min = $min<1? 1:$min;
        $max = $min+10;
        $max = $max>$all? $all:$max;

		$url = $url? $url:url(array('page'=>''));

		for($i=$min;$i<=$max;$i++){
			if($i == $cur)	$xhtml .= '<a href="javascript:void(0);" id="page_current">'.$i.'</a>';
			else $xhtml .= '<a href="'.$url.$i.'">'.$i.'</a>';
		}
		return $xhtml;
	}
}
